package com.atguigu.srb.core.task;

import com.atguigu.srb.base.dto.SmsDTO;
import com.atguigu.srb.core.entity.Lend;
import com.atguigu.srb.core.entity.LendReturn;
import com.atguigu.srb.core.entity.UserInfo;
import com.atguigu.srb.core.service.LendReturnService;
import com.atguigu.srb.core.service.LendService;
import com.atguigu.srb.core.service.UserInfoService;
import com.atguigu.srb.rabbitutil.constant.MQConst;
import com.atguigu.srb.rabbitutil.service.MQService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: Gavin
 * @Date: 7/23/2023 7:57 PM
 */
@Component
@Slf4j
public class SrbTask {
    @Resource
    UserInfoService userInfoService;
    @Resource
    LendReturnService lendReturnService;
    @Resource
    MQService mqService;
    @Resource
    LendService lendService;
    //定时任务 每分钟的0秒开始,然后每20秒执行一次 也就是0,20,40,0 . . . 一直循环下去
    @Scheduled(cron = "0/20 * * * * ?")
    public void sendLendReturnMsg(){

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        //测试@Schedule定时计划
        log.info("定时器执行的时间是:{}",new DateTime().toString("yyyy-MM-dd-HH-mm-SS"));
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        //查询最近3天以内的还款计划
        List<LendReturn> list = lendReturnService.list(Wrappers.lambdaQuery(LendReturn.class)
                        .eq(LendReturn::getStatus,0) //0表示未还的还款计划
                .lt(LendReturn::getReturnDate, new DateTime().plusDays(3)
                        //这个地方为什么是toString,而不是toDate()
                        .toString("yyyy-MM-dd")));
        // List<LendReturn> list = lendReturnService.list(); 测试用的
        if(CollectionUtils.isEmpty(list)){
            //说明近3天内没有快到期的还款计划
            return;
        }
        //能走到下面说明3天内有需要还款的计划
        list.forEach(lendReturn -> {
            //遍历每个还款计划,给对应的借款人发消息
            //获取用户的信息
            Long userId = lendReturn.getUserId();
            UserInfo userInfo = userInfoService.getById(userId);
            //获取用户的借款的信息
            Long lendId = lendReturn.getLendId();
            Lend lend = lendService.getById(lendId);
            //创建消息的对象
            SmsDTO smsDTO = new SmsDTO();
            smsDTO.setMobile(userInfo.getMobile());
            smsDTO.setType(3);
            String message = "您的借款:" + lend.getTitle() + ",第" + lendReturn.getCurrentPeriod() + "期" +"最近的还款日期是:"
                    + new DateTime(lendReturn.getReturnDate()).toString("yyyy-MM-dd") + ",请记得准时还款 ";
            smsDTO.setMessage(message);
            //发送消息
            mqService.sendMessage(MQConst.EXCHANGE_TOPIC_SMS,MQConst.ROUTING_SMS_ITEM,smsDTO);
        });
    }
}
